package cn.wp.common.core;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.wp.common.core.startup.StartupContainer;
import cn.wp.common.core.util.ApplicationContextUtil;
import cn.wp.common.core.web.WpWebMvcConfigurer;
import cn.wp.common.core.web.service.ServiceConfiguration;
import cn.wp.common.core.web.service.ServiceConfigurations;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 框架启动后运行
 * Created by chenyb on 2019/09/24
 */
@Component
@Order(1)
@Slf4j
public class WpApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) {
        log.info("Wp("+ Wp.VERSION +") Start Success, At " + DateUtil.now());
        Wp wp = Wp.self();

        ApplicationContext context = ApplicationContextUtil.getContext();
        ServiceConfigurations serviceConfigurations = context.getBean(ServiceConfigurations.class);
        WpWebMvcConfigurer webMvcConfigurer = (WpWebMvcConfigurer) context.getBean("webMvcConfigurer");

        String[] beanNames = context.getBeanNamesForType(WpSetting.class);
        log.info("SettingBeanNames = " + JSON.toJSONString(beanNames));

        // 获取所有启动器
        /*Set<Class<?>> startupClasses = ClassUtil.scanPackageByAnnotation(Wp.GlobalPackage, Starter.class);
        for(Class<?> startupClass : startupClasses){
            Startup startup = (Startup)ReflectUtil.newInstance(startupClass);
            Console.log("-- Startup " + startupClass.getName() + " start success");
            startup.start(Wp.self());
        }*/

        // 启动类容器
        StartupContainer startupContainer = ApplicationContextUtil.getBean(StartupContainer.class);
        for(String name : beanNames){
            WpSetting settingBean = (WpSetting)context.getBean(name);
            //settingBean.configProps(Aooms.self().getPropertyObject());
            settingBean.configService(serviceConfigurations);
            Map<String,ServiceConfiguration> stringServiceConfigurationMap = serviceConfigurations.getServiceConfigurationMaps();
            for(Map.Entry<String,ServiceConfiguration> entry: stringServiceConfigurationMap.entrySet()){
                Console.log("-- Register service " + entry.getKey() + " , Instance:" + entry.getValue());
            }

            settingBean.configStartup(startupContainer);
            startupContainer.startAll(wp);

            settingBean.onStart(wp);
        }
    }

}